<?php
// +----------------------------------------------------------------------
// | User Cert 资格证服务
// +----------------------------------------------------------------------
// | 主要服务于User Cert数据处理
// +----------------------------------------------------------------------
// | 错误编码头 249xxx
// +----------------------------------------------------------------------

namespace common\service;

use common\exception\LogicException;
use common\model\UserCertCategoryModel;
use common\model\UserCertModel;
use support\ErrorCode;
use support\SingletonTrait;

class UserCertService
{
    // 单例工具
    use SingletonTrait;

    /**
     * 获取用户资格证分类列表
     * @return mixed
     */
    public function getUserCertCategoryList()
    {
        $userCertCategoryModel = model(UserCertCategoryModel::class);
        $list = $userCertCategoryModel->order(['created desc'])->select();
//        foreach ($list as &$item) {
//            $item['created'] = get_format_date($item['created'], 1);
//        }
        return $list;
    }

    /**
     * 创建用户资格证分类
     * @param $data
     * @return array|bool
     * @throws \Exception
     */
    public function createCertCategory($data)
    {
        $userCertCategoryModel = model(UserCertCategoryModel::class);
        // 执行新增操作
        $resData = $userCertCategoryModel->addItem($data);
        if (!$resData) {
            // 通用创建失败错误码 001
            throw new LogicException($userCertCategoryModel->getError(), ErrorCode::CERT_CATEGORY_CREATE_FAILURE);
        } else {
            // 返回成功数据
            return $resData;
        }
    }

    /**
     * 更新用户资格证分类
     * @param $data
     * @return array|bool
     * @throws \Exception
     */
    public function modifyCertCategory($data)
    {
        $userCertCategoryModel = model(UserCertCategoryModel::class);
        $resData = $userCertCategoryModel->modifyItem($data);
        if (!$resData) {
            // 通用修改失败错误码 002
            throw new LogicException($userCertCategoryModel->getError(), ErrorCode::CERT_CATEGORY_MODIFY_FAILURE);
        } else {
            // 返回成功数据
            return $resData;
        }
    }

    /**
     * 删除用户资格证分类
     * @param $filter
     * @return array
     */
    public function deleteCertCategory($filter)
    {

        $userCertCategoryModel = model(UserCertCategoryModel::class);

        // 获取当前模块删除主键
        $masterIdData = $userCertCategoryModel->field('id')->where($filter)->select();

        if (!empty($masterIdData)) {
            $masterIds = join(',', array_column($masterIdData, 'id'));
            $resData = $userCertCategoryModel->deleteItem([
                'id' => ["IN", $masterIds]
            ]);

            if (!$resData) {
                // 通用删除失败错误码 003
                throw new LogicException($userCertCategoryModel->getError(), ErrorCode::CERT_CATEGORY_DELETE_FAILURE);
            } else {
                // 返回成功数据

                // 删除相关联资格证
                $userCertModel = model(UserCertModel::class);
                $userCertModel->where(['user_cert_category_id' => ['in', $masterIds]])->delete();

                return ['ids' => $masterIds];
            }

        } else {
            throw new LogicException('Delete item does not exist.', ErrorCode::DELETE_ITEM_NOT_EXIST);
        }
    }

    /**
     * 创建用户资格证
     * @param $data
     * @return array|bool
     * @throws \Exception
     */
    public function createUserCert($data)
    {
        // 获取属性sku ids
        $stepService = StepService::getInstance();
        $attributeIds = $stepService->getStepSkuIdsByStepAttributeIds($data['attribute_ids']);

        if (empty($attributeIds)) {
            throw new LogicException('Incomplete Attribute Selection.', ErrorCode::INCOMPLETE_ATTRIBUTE_SELECTION);
        }

        // 添加数据
        $userCertAddData = [
            'level' => $data['level'],
            'level_category' => $data['level_category'],
            'user_cert_category_id' => $data['user_cert_category_id'],
            'base_man_hour' => $data['base_man_hour'],
            'step_sku_ids' => $attributeIds,
            'step_attribute_config' => $data['attribute_ids']
        ];

        $userCertModel = model(UserCertModel::class);
        // 执行新增操作
        $resData = $userCertModel->addItem($userCertAddData);
        if (!$resData) {
            // 通用创建失败错误码 011
            throw new LogicException($userCertModel->getError(), ErrorCode::CERT_CATEGORY_CREATE_FAILURE);
        } else {
            // 返回成功数据
            return $resData;
        }
    }

    /**
     * 更新用户资格证
     * @param $data
     * @return array|bool
     * @throws \Exception
     */
    public function modifyUserCert($data)
    {
        $userCertUpdateData = [];

        foreach ($data as $key => $value) {
            if ($key !== 'attribute_ids') {
                $userCertUpdateData[$key] = $value;
            } else {
                $userCertUpdateData['step_attribute_config'] = $value;
            }
        }

        if (array_key_exists('attribute_ids', $data)) {
            // 获取属性sku ids
            $stepService = StepService::getInstance();
            $attributeIds = $stepService->getStepSkuIdsByStepAttributeIds($data['attribute_ids']);

            if (empty($attributeIds)) {
                throw new LogicException('Incomplete Attribute Selection.', ErrorCode::INCOMPLETE_ATTRIBUTE_SELECTION);
            }

            $userCertUpdateData['step_sku_ids'] = $attributeIds;
        }

        $userCertModel = model(UserCertModel::class);
        $resData = $userCertModel->modifyItem($userCertUpdateData);
        if (!$resData) {
            // 通用修改失败错误码 012
            throw new LogicException($userCertModel->getError(), ErrorCode::CERT_CATEGORY_MODIFY_FAILURE);
        } else {
            // 返回成功数据
            return $resData;
        }
    }


    /**
     * 删除更新用户资格证
     * @param $filter
     * @return array
     */
    public function deleteUserCert($filter)
    {
        $userCertModel = model(UserCertModel::class);

        // 获取当前模块删除主键
        $masterIdData = $userCertModel->field('id')->where($filter)->select();

        if (!empty($masterIdData)) {
            $masterIds = join(',', array_column($masterIdData, 'id'));
            $resData = $userCertModel->deleteItem([
                'id' => ["IN", $masterIds]
            ]);

            if (!$resData) {
                // 通用删除失败错误码 013
                throw new LogicException($userCertModel->getError(), ErrorCode::CERT_CATEGORY_DELETE_FAILURE);
            } else {
                // 返回成功数据
                return ['ids' => $masterIds];
            }

        } else {
            throw new LogicException('Delete item does not exist.', ErrorCode::DELETE_ITEM_NOT_EXIST);
        }
    }

    /**
     * 获取用户资格证
     * @param $filter
     * @return mixed
     */
    public function selectUserCert($filter)
    {
        $userCertModel = model(UserCertModel::class);
        $userCertData = $userCertModel->selectData(['fields' => '', 'filter' => $filter]);

        return $userCertData['rows'];
    }

    /**
     * 通过sku匹配产能等级
     * @param array $stepSkuIds
     * @return mixed
     */
    public function matchUserCertBySku(array $stepSkuIds)
    {
        $userCertModel = model(UserCertModel::class);
        $filter = "";
        foreach ($stepSkuIds as $stepSkuId) {
            $filter .= " FIND_IN_SET($stepSkuId, step_sku_ids) OR";
        }
        $filter = trim($filter, "OR");

        return $userCertModel->where($filter)->order("`level_category` DESC,`level` ASC")->find();
    }

    /**
     * 查询用户资格证树
     * @param $param
     * @return mixed
     */
    public function selectUserCertTree($param)
    {
        $categories = model(UserCertCategoryModel::class)->selectData($param);
        $categories = $categories['rows'];

        $categoryIdArray = array_column($categories, 'id');
        $certs = model(UserCertModel::class)
            ->where(['user_cert_category_id' => ['IN', implode(',', $categoryIdArray)]])
            ->field("id,base_man_hour,level name,level_category,user_cert_category_id")
            ->select();
        $certsMap = array_group_by($certs, 'user_cert_category_id');
        foreach ($categories as &$category) {
            $category['real_id'] = $category['id'];
            $category['children'] = $certsMap[$category['id']] ?? [];
            $category['id'] = 'category_' . $category['id'];
        }
        return $categories;
    }
}
